import json
import numpy as np
from io import BytesIO
from typing import List
import face_recognition
from PIL import Image, ImageDraw
from fastapi.responses import JSONResponse, RedirectResponse, FileResponse
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi import FastAPI, Request, File, UploadFile, Depends
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
import base64
import cv2
import secrets
from datetime import datetime, timedelta
import random
from pathlib import Path
import os

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/data", StaticFiles(directory="data"), name="data")
templates = Jinja2Templates(directory="templates")

# 修改用户数据库初始化部分
def load_users():
    """从文件加载用户数据"""
    try:
        with open('data/users.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        # 如果文件不存在或损坏，创建默认用户数据
        default_users = {
            "admin": {
                "password": "admin",
                "token": None
            }
        }
        # 保存默认用户数据
        with open('data/users.json', 'w', encoding='utf-8') as f:
            json.dump(default_users, f, ensure_ascii=False, indent=2)
        return default_users

# 初始化用户数据
USERS = load_users()

# 用于登录的数据模型
class LoginData(BaseModel):
    username: str
    password: str

# 用于存储会话token
sessions = {}

# 创建数据存储目录
if not os.path.exists('data'):
    os.makedirs('data')

class UserStats:
    def __init__(self):
        self.stats_file = "data/user_stats.json"
        self.load_stats()
    
    def load_stats(self):
        """从文件加载用户统计数据"""
        try:
            with open(self.stats_file, 'r', encoding='utf-8') as f:
                self.user_stats = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            self.user_stats = {}
    
    def save_stats(self):
        """保存用户统计数据到文件"""
        with open(self.stats_file, 'w', encoding='utf-8') as f:
            json.dump(self.user_stats, f, ensure_ascii=False, indent=2)
    
    def update_login(self, username):
        """更新用户登录信息"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        if username not in self.user_stats:
            self.user_stats[username] = {
                "last_login": current_time,
                "login_count": 1,
                "total_operations": 0,
                "success_operations": 0,
                "last_operation_time": None
            }
        else:
            self.user_stats[username]["last_login"] = current_time
            self.user_stats[username]["login_count"] += 1
        
        self.save_stats()
    
    def update_operation(self, username, success=True):
        """更新用户操作信息"""
        if username not in self.user_stats:
            return
        
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.user_stats[username]["total_operations"] += 1
        if success:
            self.user_stats[username]["success_operations"] += 1
        self.user_stats[username]["last_operation_time"] = current_time
        self.save_stats()
    
    def get_user_stats(self, username):
        """获取用户统计信息"""
        if username not in self.user_stats:
            return {
                "username": username,
                "password": USERS[username]["password"] if username in USERS else "",
                "last_login": "-",
                "login_count": 0,
                "total_operations": 0,
                "success_operations": 0,
                "success_rate": "0%",
                "last_operation_time": "-",
                "user_info": {
                    "role": "管理员" if username == "admin" else "普通用户",
                    "created_time": "2024-01-01 00:00:00"
                }
            }
        
        stats = self.user_stats[username]
        total = stats["total_operations"]
        success = stats["success_operations"]
        success_rate = f"{round((success / total * 100), 1)}%" if total > 0 else "0%"
        
        return {
            "username": username,
            "password": USERS[username]["password"] if username in USERS else "",
            "last_login": stats["last_login"],
            "login_count": stats["login_count"],
            "total_operations": total,
            "success_operations": success,
            "success_rate": success_rate,
            "last_operation_time": stats["last_operation_time"],
            "user_info": {
                "role": "管理员" if username == "admin" else "普通用户",
                "created_time": stats.get("created_time", "2024-01-01 00:00:00")
            }
        }

# 创建用户统计实例
user_stats = UserStats()

def verify_token(token: str = None):
    """验证token是否有效"""
    if not token or token not in sessions:
        raise HTTPException(status_code=401, detail="未登录或会话已过期")
    return sessions[token]['username']  # 返回用户名而不是整个session对象

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """捕获默认框架返回的异常信息格式，修改为规定格式"""
    return JSONResponse({"success": False,
                         "code": 400,
                         "msg": f"接口参数传递错误",
                         "data": exc.errors()}
                        )

@app.get("/")
async def root(request: Request):
    """重定向到登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})

@app.get("/main")
async def main_page(request: Request, token: str = None):
    """主页面"""
    try:
        verify_token(token)
        return templates.TemplateResponse("index.html", {"request": request})
    except HTTPException:
        return RedirectResponse(url="/")

@app.post("/login")
async def login(data: LoginData):
    """处理登录请求"""
    try:
        if data.username not in USERS:
            return {
                "success": False,
                "code": 401,
                "msg": "用户名不存在"
            }
        
        if USERS[data.username]["password"] != data.password:
            return {
                "success": False,
                "code": 401,
                "msg": "密码错误"
            }
            
        token = secrets.token_urlsafe(32)
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 更新用户统计信息
        user_stats.update_login(data.username)
        
        # 更新会话信息
        sessions[token] = {
            'username': data.username,
            'last_login': current_time
        }
        
        return {
            "success": True,
            "code": 200,
            "msg": "登录成功",
            "data": {"token": token}
        }
    except Exception as e:
        return {"success": False, "code": 500, "msg": str(e)}

@app.get("/logout")
async def logout(token: str = None):
    """处理登出请求"""
    if token in sessions:
        del sessions[token]
    return RedirectResponse(url="/")

@app.post("/faceapi/v1/detectBox")
async def detect_box(request: Request, imgFile: UploadFile = File(...)):
    """获取人脸检测框坐标"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_boxes = face_recognition.face_locations(image_array)
        
        # 更新用户操作统计
        user_stats.update_operation(username, success=True)
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        # 添加操作记录
        stats.detect_count += 1
        stats.add_record("人脸检测", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "检测完成",
            "data": {
                "boxes": face_boxes,
                "count": len(face_boxes)
            }
        }
    except Exception as e:
        # 更新失败统计
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        if 'username' in locals():
            user_stats.update_operation(username, success=False)
            stats.add_record("人脸检测", "失败", round(process_time), username)
        return {"success": False, "code": 500, "msg": str(e)}

@app.post("/faceapi/v1/detectFace")
async def detect_face(request: Request, imgFile: UploadFile = File(...)):
    """提取人脸图片"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_locations = face_recognition.face_locations(image_array)
        faces = []
        for face_location in face_locations:
            top, right, bottom, left = face_location
            face_image = image_array[top:bottom, left:right]
            face_pil = Image.fromarray(face_image)
            buffered = BytesIO()
            face_pil.save(buffered, format="JPEG")
            face_base64 = base64.b64encode(buffered.getvalue()).decode()
            faces.append(face_base64)

        # 更新用户操作统计
        user_stats.update_operation(username, success=True)
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        # 添加操作记录
        stats.detect_count += 1
        stats.add_record("人脸提取", "成功", round(process_time), username)

        return {
            "success": True,
            "code": 200,
            "msg": "提取完成",
            "data": {
                "faces": faces,
                "count": len(faces)
            }
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        if 'username' in locals():
            user_stats.update_operation(username, success=False)
            stats.add_record("人脸提取", "失败", round(process_time), username)
        return {"success": False, "code": 500, "msg": str(e), "data": None}

@app.post("/faceapi/v1/detectDrawBox")
async def detect_draw_box(request: Request, imgFile: UploadFile = File(...)):
    """在原图上绘制人脸框"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_locations = face_recognition.face_locations(image_array)
        
        # 绘制人脸框
        draw_image = Image.fromarray(image_array)
        draw = ImageDraw.Draw(draw_image)
        for face_location in face_locations:
            top, right, bottom, left = face_location
            draw.rectangle(((left, top), (right, bottom)), outline=(0, 255, 0), width=2)
        
        # 转换为base64
        buffered = BytesIO()
        draw_image.save(buffered, format="JPEG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode()
        
        # 更新用户操作统计
        user_stats.update_operation(username, success=True)
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        # 添加操作记录
        stats.detect_count += 1
        stats.add_record("人脸框绘制", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "绘制完成",
            "data": {
                "image": img_base64,
                "count": len(face_locations)
            }
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        if 'username' in locals():
            user_stats.update_operation(username, success=False)
            stats.add_record("人脸框绘制", "失败", round(process_time), username)
        return {"success": False, "code": 500, "msg": str(e), "data": None}

@app.post("/faceapi/v1/landmarksPoint")
async def detect_landmarks_point(request: Request, imgFile: UploadFile = File(...)):
    """获取人脸特征点坐标"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_landmarks_list = face_recognition.face_landmarks(image_array)
        
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.landmarks_count += 1
        stats.add_record("特征点检测", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "检测完成",
            "data": {
                "face_landmarks_list": face_landmarks_list
            }
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.add_record("特征点检测", "失败", round(process_time), username if 'username' in locals() else None)
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

@app.post("/faceapi/v1/landmarksDraw")
async def detect_landmarks_draw(request: Request, imgFile: UploadFile = File(...)):
    """在图片上绘制特征点"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_landmarks_list = face_recognition.face_landmarks(image_array)
        
        # 转换为PIL图片以便绘制
        pil_image = Image.fromarray(image_array)
        draw = ImageDraw.Draw(pil_image)
        
        # 绘制所有特征点
        for face_landmarks in face_landmarks_list:
            for facial_feature in face_landmarks.keys():
                points = face_landmarks[facial_feature]
                for point in points:
                    draw.ellipse([
                        (point[0] - 2, point[1] - 2),
                        (point[0] + 2, point[1] + 2)
                    ], fill='red')
                draw.line(points + [points[0]], fill='red', width=1)
        
        # 转换为base64
        buffered = BytesIO()
        pil_image.save(buffered, format="JPEG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode()
        
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.landmarks_count += 1
        stats.add_record("特征点绘制", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "处理完成",
            "data": {
                "image": img_base64
            }
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.add_record("特征点绘制", "失败", round(process_time), username if 'username' in locals() else None)
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

@app.post("/faceapi/v1/landmarksMakeup")
async def detect_landmarks_makeup(request: Request, imgFile: UploadFile = File(...)):
    """添加虚拟美妆效果"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        # 读取图片
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_landmarks_list = face_recognition.face_landmarks(image_array)
        
        # 转换为PIL图片以便绘制
        pil_image = Image.fromarray(image_array)
        draw = ImageDraw.Draw(pil_image, 'RGBA')
        
        # 为每个人脸添加美妆效果
        for face_landmarks in face_landmarks_list:
            # 绘制眼影
            for eye in ['left_eye', 'right_eye']:
                points = face_landmarks[eye]
                draw.polygon(points, fill=(255, 182, 193, 80))  # 淡粉色眼影
            
            # 绘制唇彩
            points = face_landmarks['top_lip'] + face_landmarks['bottom_lip']
            draw.polygon(points, fill=(255, 20, 147, 120))  # 深粉色唇彩
            
            # 绘制腮红
            left_cheek = [(p[0]-20, p[1]) for p in face_landmarks['nose_tip']]
            right_cheek = [(p[0]+20, p[1]) for p in face_landmarks['nose_tip']]
            draw.polygon(left_cheek, fill=(255, 192, 203, 100))
            draw.polygon(right_cheek, fill=(255, 192, 203, 100))
        
        # 转换为base64
        buffered = BytesIO()
        pil_image.save(buffered, format="JPEG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode()

        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.landmarks_count += 1
        stats.add_record("虚拟美妆", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "处理完成",
            "data": {
                "image": img_base64
            }
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.add_record("虚拟美妆", "失败", round(process_time), username if 'username' in locals() else None)
        return {"success": False, "code": 500, "msg": str(e), "data": None}

@app.post("/faceapi/v1/recognizeCompareImage")
async def upload_image(request: Request, imgFile1: UploadFile = File(...), imgFile2: UploadFile = File(...)):
    """人脸比较"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        
        # 读取并转换图片
        image_array1 = face_recognition.load_image_file(BytesIO(await imgFile1.read()))
        image_array2 = face_recognition.load_image_file(BytesIO(await imgFile2.read()))
        
        # 获取人脸编码
        encodings1 = face_recognition.face_encodings(image_array1)
        if not encodings1:
            raise ValueError("第一张图片未检测到人脸")
        
        encodings2 = face_recognition.face_encodings(image_array2)
        if not encodings2:
            raise ValueError("第二张图片未检测到人脸")
        
        # 使用第一个检测到的人脸进行比较
        encoding1 = encodings1[0]
        encoding2 = encodings2[0]
        
        results = face_recognition.compare_faces([encoding1], encoding2)
        results = np.array(results).tolist()
        
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.compare_count += 1
        stats.add_record("面部对比", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "比较完成",
            "data": {"compare_result": results}
        }
    except ValueError as ve:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        if 'username' in locals():
            stats.add_record("面部对比", "失败", round(process_time), username)
        return {
            "success": False,
            "code": 400,
            "msg": str(ve),
            "data": None
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        if 'username' in locals():
            stats.add_record("面部对比", "失败", round(process_time), username)
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

@app.post("/faceapi/v1/recognizeEncoding")
async def upload_image(request: Request, imgFile: UploadFile = File(...)):
    """特征编码"""
    token = request.headers.get("Authorization")
    start_time = datetime.now()
    try:
        username = verify_token(token)
        image_array = face_recognition.load_image_file(BytesIO(await imgFile.read()))
        face_encoding = face_recognition.face_encodings(image_array, model="cnn")[0]
        face_encoding = np.array(face_encoding).tolist()
        
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.encoding_count += 1
        stats.add_record("特征编码", "成功", round(process_time), username)
        
        return {
            "success": True,
            "code": 200,
            "msg": "编码完成",
            "data": {"encoding": face_encoding}
        }
    except Exception as e:
        process_time = (datetime.now() - start_time).total_seconds() * 1000
        stats.add_record("特征编码", "失败", round(process_time), username if 'username' in locals() else None)
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

@app.post("/faceapi/v1/recognizeCompareEncoding")
async def upload_encoding_list(encodings: List[List[float]]=[[123.1, 123.1], [456.1, 456.2]], encoding: List[float]=[123.2, 123.1], tolerance: float = 0.5):
    """
    人脸比较 返回比较结果 True False
    :param encoding_list: [encoding1, encoding2, encoding3, ...]
    :param encoding: [ 0.00212635  0.18151696 ...  0.08942952 -0.02890663]
    :param show: 是否打印比较结果
    :return: 返回比较结果
    """
    try:
        encodings = np.array(encodings, dtype=np.float64)
        encoding = np.array(encoding, dtype=np.float64)
        face_distances = face_recognition.face_distance(encodings, encoding)
        face_distances = np.array(face_distances < tolerance).tolist()
        return {"success": True,
                "code": 200,
                "msg": f"返回比较结果 [True] or [False]",
                "data": {"compare_result": face_distances}
                }
    except Exception as e:
        return {"success": False,
                "code": 500,
                "msg": str(e),
                "data": None}

@app.get("/pages/{page_name}")
async def get_page(page_name: str, request: Request):
    """获取功能页面"""
    try:
        return templates.TemplateResponse(f"pages/{page_name}.html", {"request": request})
    except Exception as e:
        return JSONResponse(
            status_code=404,
            content={"error": f"Page not found: {str(e)}"}
        )

# 添加统计数据路由
@app.get("/api/stats")
async def get_stats(request: Request):
    """获取系统统计数据"""
    token = request.headers.get("Authorization")
    try:
        verify_token(token)
        return {
            "success": True,
            "code": 200,
            "msg": "获取统计数据成功",
            "data": {
                "system_stats": stats.get_system_stats(),
                "recent_records": stats.recent_records
            }
        }
    except Exception as e:
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

# 添加使用记录路由
@app.get("/api/usage-history")
async def get_usage_history(request: Request):
    """获取使用记录"""
    token = request.headers.get("Authorization")
    try:
        verify_token(token)
        return {
            "success": True,
            "code": 200,
            "msg": "获取使用记录成功",
            "data": {
                "history": stats.usage_history
            }
        }
    except Exception as e:
        return {
            "success": False,
            "code": 500,
            "msg": str(e),
            "data": None
        }

# 添加获取用户信息的路由
@app.get("/api/user-info")
async def get_user_info(request: Request):
    token = request.headers.get("Authorization")
    try:
        username = verify_token(token)
        stats = user_stats.get_user_stats(username)
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        return {
            "success": True,
            "code": 200,
            "msg": "获取用户信息成功",
            "data": {
                "username": username,
                "currentLoginTime": current_time,
                "lastLogin": stats["last_login"],
                "totalOperations": stats["total_operations"],
                "successOperations": stats["success_operations"],
                "successRate": stats["success_rate"],
                "lastOperationTime": stats["last_operation_time"]
            }
        }
    except Exception as e:
        return {"success": False, "code": 500, "msg": str(e)}

# 添加获取用户密码的路由
@app.get("/api/user-password")
async def get_user_password(request: Request):
    token = request.headers.get("Authorization")
    try:
        username = verify_token(token)
        return {
            "success": True,
            "code": 200,
            "msg": "获取密码成功",
            "data": {
                "password": USERS[username]["password"]
            }
        }
    except Exception as e:
        return {"success": False, "code": 500, "msg": str(e)}

# 添加修改密码的路由
@app.post("/api/change-password")
async def change_password(request: Request):
    token = request.headers.get("Authorization")
    try:
        username = verify_token(token)
        data = await request.json()
        old_password = data.get("oldPassword")
        new_password = data.get("newPassword")
        
        if USERS[username]["password"] != old_password:
            return {
                "success": False,
                "code": 400,
                "msg": "原密码错误"
            }
        
        USERS[username]["password"] = new_password
        
        # 保存到文件
        with open("data/users.json", "w", encoding="utf-8") as f:
            json.dump(USERS, f, ensure_ascii=False, indent=2)
        
        return {
            "success": True,
            "code": 200,
            "msg": "密码修改成功"
        }
    except Exception as e:
        return {"success": False, "code": 500, "msg": str(e)}

# 添加一个简单的内存数据存储
class Statistics:
    def __init__(self):
        self.stats_file = "data/stats_data.json"
        self.load_stats()
    
    def load_stats(self):
        """从文件加载统计数据"""
        try:
            with open(self.stats_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.detect_count = data.get('detect_count', 0)
                self.landmarks_count = data.get('landmarks_count', 0)
                self.compare_count = data.get('compare_count', 0)
                self.encoding_count = data.get('encoding_count', 0)
                self.recent_records = data.get('recent_records', [])
                self.user_operations = data.get('user_operations', {})
        except (FileNotFoundError, json.JSONDecodeError):
            self.detect_count = 0
            self.landmarks_count = 0
            self.compare_count = 0
            self.encoding_count = 0
            self.recent_records = []
            self.user_operations = {}
    
    def save_stats(self):
        """保存统计数据到文件"""
        data = {
            'detect_count': self.detect_count,
            'landmarks_count': self.landmarks_count,
            'compare_count': self.compare_count,
            'encoding_count': self.encoding_count,
            'recent_records': self.recent_records,
            'user_operations': self.user_operations
        }
        with open(self.stats_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def add_record(self, function_name, status, process_time, username=None):
        """添加记录并保存"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 更新计数器
        if function_name == "人脸检测":
            self.detect_count += 0
        elif function_name == "特征点检测":
            self.landmarks_count += 0
        elif function_name == "面部对比":
            self.compare_count += 0
        elif function_name == "特征编码":
            self.encoding_count += 0
            
        # 添加记录
        record = {
            "time": current_time,
            "function": function_name,
            "status": status,
            "processTime": process_time,
            "username": username
        }
        
        # 更新最近记录
        self.recent_records.insert(0, record)
        self.recent_records = self.recent_records[:20]  # 保留最近20条记录
        
        # 更新用户操作统计
        if username:
            if username not in self.user_operations:
                self.user_operations[username] = {
                    "total_operations": 0,
                    "success_operations": 0,
                    "last_operation_time": None,
                    "total_response_time": 0
                }
            
            user_stats = self.user_operations[username]
            user_stats["total_operations"] += 1
            if status == "成功":
                user_stats["success_operations"] += 1
            user_stats["last_operation_time"] = current_time
            user_stats["total_response_time"] += process_time
        
        # 保存到文件
        self.save_stats()

    def get_user_stats(self, username):
        """获取用户统计信息"""
        if username not in self.user_operations:
            return {
                "total_operations": 0,
                "success_operations": 0,
                "success_rate": 0,
                "last_operation_time": None,
                "avg_response_time": 0
            }
        
        stats = self.user_operations[username]
        total = stats["total_operations"]
        success = stats["success_operations"]
        
        return {
            "total_operations": total,
            "success_operations": success,
            "success_rate": round((success / total * 100), 1) if total > 0 else 0,
            "last_operation_time": stats["last_operation_time"],
            "avg_response_time": round(stats["total_response_time"] / total) if total > 0 else 0
        }

    def get_system_stats(self):
        """获取系统统计信息"""
        total_operations = sum(user["total_operations"] for user in self.user_operations.values())
        total_success = sum(user["success_operations"] for user in self.user_operations.values())
        total_response_time = sum(user["total_response_time"] for user in self.user_operations.values())
        
        return {
            "detect_count": self.detect_count,
            "landmarks_count": self.landmarks_count,
            "compare_count": self.compare_count,
            "encoding_count": self.encoding_count,
            "success_rate": round((total_success / total_operations * 100), 1) if total_operations > 0 else 0,
            "avg_response_time": round(total_response_time / total_operations) if total_operations > 0 else 0
        }

# 创建统计实例
stats = Statistics()

@app.get("/api/test-images")
async def get_test_images(type: str):
    """获取测试图片列表"""
    try:
        examples_dir = Path("data/examples")
        if not examples_dir.exists():
            return {"images": []}
            
        images = []
        if type == "compare":
            # 对于对比功能，查找成对的图片
            pairs = []
            # 遍历目录查找所有匹配的图片对
            for i in range(1, 10):  # 最多查找10组
                pair_1 = examples_dir / f"compare_example{i}_1.jpg"
                pair_2 = examples_dir / f"compare_example{i}_2.jpg"
                if pair_1.exists() and pair_2.exists():
                    pairs.append(f"compare_example{i}_1.jpg,compare_example{i}_2.jpg")
            images = pairs
            
            # 如果没有找到任何图片对，返回空列表
            if not images:
                return {"images": []}
        else:
            # 其他功能查找单张图片
            pattern = f"{type}_example*.jpg"
            images = [f.name for f in examples_dir.glob(pattern)]
            
        return {"images": sorted(images)}
    except Exception as e:
        print(f"Error in get_test_images: {str(e)}")  # 添加错误日志
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8101)
